const express = require('express')
const axios = require('axios')
const { get, del, set } = require('../utils/cache')

const router = express.Router()

const CACHE_KEY = 'zhihu'
const TITLE = '知乎'

// const headers = {
//     'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
// }

router.get('/zhihu', async (req, res) => {
    if (req.query.timestamp) {
        del(CACHE_KEY)
    }
    let data = get(CACHE_KEY)
    if (data) {
        res._op('success', 1, data)
        console.log('在缓存中获取');
    }
    else {
        try {
            const { data: result } = await axios.get('https://www.zhihu.com/api/v4/creators/rank/hot?domain=0&period=hour')
            const list = result.data.map(v => {
                return {
                    title: v.question.title,
                    desc: v.question.title,
                    hotCount: v.reaction.pv,
                    url: v.question.url
                }
            })
            const updateTime = new Date().getTime()
            data = {
                title: TITLE,
                total: list.length,
                list,
                updateTime
            }
            set(CACHE_KEY, data)
            res._op('success', 1, data)
            console.log('通过服务获取');
        } catch (error) {
            res._op(error)
        }
    }
})

module.exports = router
